package com.estagio.daoHibernate;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Restrictions;

import util.HibernateUtil;

import com.estagio.entity.Matricula;

public class MatriculaDao {

	private Session sessao;
	

	public void save(Matricula matricula) {
		if((matricula.getIdMatricula() == null) || (matricula.getIdMatricula() == 0)) {
			this.sessao = HibernateUtil.getSession().getCurrentSession();
			this.sessao.save(matricula);
		} else {
			this.sessao = HibernateUtil.getSession().getCurrentSession();
			this.sessao.update(matricula);
			this.sessao.flush();
			this.sessao.refresh(matricula);
		}
		
	}

	public Session getSessao() {
		return sessao;
	}

	public void setSessao(Session sessao) {
		this.sessao = sessao;
	}

	public List<Matricula> list() {
		System.out.println("entrou");
		try {
			this.sessao = HibernateUtil.getSession().getCurrentSession();
			List<Matricula> lista = (List<Matricula>) this.sessao.createQuery("From Matricula ").list();		
		
			return lista;
		} catch (Exception e) {
			System.out.println("Erro no DaoHibernate: " + e);
		}

		return null;
	}

	public List<Matricula> find(Matricula matricula) {
		this.sessao =  HibernateUtil.getSession().getCurrentSession();
		List<Matricula> lista;
		
		if(matricula.getAluno() != null) {
			if(matricula.getAluno().getIdAluno() != null) {
				if(matricula.getAluno().getIdAluno() != 0) {
					try {
						lista = this.sessao.createCriteria(Matricula.class)
								.createCriteria("aluno")
									.add(Restrictions.eq("idAluno", matricula.getAluno().getIdAluno()))
								.list();
						return lista;
					} catch (Exception e) {
						return null;
					}
				}
			}
			
			if(matricula.getAluno().getNome() != null) {
				if(!(matricula.getAluno().getNome().equals(""))) {
					try {
						lista = this.sessao.createCriteria(Matricula.class)
								.createCriteria("aluno")
									.add(Restrictions.like("nome", matricula.getAluno().getNome(), MatchMode.ANYWHERE).ignoreCase())
								.list();
						return lista;
					} catch (Exception e) {
						return null;
					}
				}
			}
		}
		
		
		try {
			lista = this.sessao.createCriteria(Matricula.class)
					.list();
			return lista;
		} catch (Exception e) {
			return null;
		}
	}

	public List<Matricula> findByPrimaryKey(Matricula matricula) {
		Matricula auxMatricula = matricula;
		Integer idMatricula = matricula.getIdMatricula();
		this.sessao = HibernateUtil.getSession().getCurrentSession();
		String hql = "from Matricula p where p.idMatricula = :idMatricula";
		Query select = this.sessao.createQuery(hql);
		select.setInteger("idMatricula", idMatricula);
		List listaMatricula = select.list();
		return listaMatricula;
	}

	public void delete(Matricula matricula) {
		this.sessao.delete(matricula);		
	}

	
}
